package com.glowdayz.glowmee;

import android.content.Context;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.glowdayz.common.SoftKeyboardDectectorView;
import com.glowdayz.common.SoftKeyboardDectectorView.OnHiddenKeyboardListener;
import com.glowdayz.common.SoftKeyboardDectectorView.OnShownKeyboardListener;

public class ListProduct extends Fragment implements OnClickListener {
	
	LinearLayout searchLayout = null, bodyLayout = null, bottomLayout = null, bodyButtonLayout = null, hideLayout = null, ll_fragment = null;
    ImageView categoryBt = null, brandBt = null;
    ImageView searchProductBt = null, searchBrandBt = null;
	EditText searchText = null;
	
	boolean keyCheck = false, isSearch = true;
	
	String searchTextValue = "";
	
	int isRoot = 1;
	
	DrawerLayout dlDrawerIndex;
	ImageView guestBt = null;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        View nowView = inflater.inflate(R.layout.activity_list_product, container, false);
        
        dlDrawerIndex = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
		dlDrawerIndex.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		
		guestBt = (ImageView) getActivity().findViewById(R.id.guestBt);
        
        searchLayout = (LinearLayout) nowView.findViewById(R.id.searchLayout);
		bodyLayout = (LinearLayout) nowView.findViewById(R.id.bodyLayout);
		bottomLayout = (LinearLayout) getActivity().findViewById(R.id.bottomLayout);
		bodyButtonLayout = (LinearLayout) nowView.findViewById(R.id.bodyButtonLayout);
		hideLayout = (LinearLayout) nowView.findViewById(R.id.hideLayout);
		ll_fragment = (LinearLayout) nowView.findViewById(R.id.ll_fragment);
		searchLayout.setVisibility(View.GONE);
		
		categoryBt = (ImageView) nowView.findViewById(R.id.categoryBt);
		categoryBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		
		brandBt = (ImageView) nowView.findViewById(R.id.brandBt);
		brandBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		
		searchProductBt = (ImageView) nowView.findViewById(R.id.searchProductBt);
		searchBrandBt = (ImageView) nowView.findViewById(R.id.searchBrandBt);
		categoryBt.setOnClickListener(this);
		brandBt.setOnClickListener(this);
		searchProductBt.setOnClickListener(this);
		searchBrandBt.setOnClickListener(this);
		
		searchText = (EditText) nowView.findViewById(R.id.searchText);
		
		hideLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
				bodyButtonLayout.setVisibility(View.VISIBLE);
       		 	searchLayout.setVisibility(View.GONE);
				hideLayout.setVisibility(View.GONE);
				return true;
			}
		});
		
		TextWatcher watcher = new TextWatcher() {
		    @Override
		    public void afterTextChanged(Editable s) {
		         //텍스트 변경 후 발생할 이벤트를 작성.
		    }
		 
		    @Override
		    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		         //텍스트의 길이가 변경되었을 경우 발생할 이벤트를 작성.
		    }
		 
		    @Override
		    public void onTextChanged(CharSequence s, int start, int before, int count) {
		         //텍스트가 변경될때마다 발생할 이벤트를 작성.
		         if (searchText.isFocusable()) {
		        	 searchTextValue = searchText.getText().toString().trim();
		        	 
		        	 if (searchTextValue.equals("")) {
		        		 hideLayout.setVisibility(View.VISIBLE);
		        		 fragmentReplace(isRoot);
		        	 } else if (isRoot == 1) {
		        		 bodyButtonLayout.setVisibility(View.GONE);
		        		 searchLayout.setVisibility(View.VISIBLE);
		        		 hideLayout.setVisibility(View.GONE);
		        		 fragmentReplace(3);
		        	 } else if (isRoot == 2) {
		        		 bodyButtonLayout.setVisibility(View.GONE);
		        		 searchLayout.setVisibility(View.VISIBLE);
		        		 hideLayout.setVisibility(View.GONE);
		        		 fragmentReplace(4);
		        	 }
		        	 
		        	 //Toast.makeText(ListProduct.this, searchTextValue, Toast.LENGTH_SHORT).show();
		         }
		    }
		};
		 
		searchText.addTextChangedListener(watcher);
		
		final SoftKeyboardDectectorView softKeyboardDecector = new SoftKeyboardDectectorView(getActivity());
		getActivity().addContentView(softKeyboardDecector, new FrameLayout.LayoutParams(-1, -1));
		 
		softKeyboardDecector.setOnShownKeyboard(new OnShownKeyboardListener() {
		 
		    @Override
		    public void onShowSoftKeyboard() {
		    	bodyButtonLayout.setVisibility(View.GONE);
       		 	searchLayout.setVisibility(View.VISIBLE);
				bottomLayout.setVisibility(View.GONE);
		    	
				if (searchTextValue.equals("")) {
		    		hideLayout.setVisibility(View.VISIBLE);
		    	}
		    	
		    	hideLayout.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
						return true;
					}
				});
		    	
		    	if (isRoot == 1) {
		    		searchProductBt.setImageResource(R.drawable.search_left_on);
		    		searchBrandBt.setImageResource(R.drawable.search_right_off);
		    	} else if (isRoot == 2) {
		    		searchBrandBt.setImageResource(R.drawable.search_right_on);
		    		searchProductBt.setImageResource(R.drawable.search_left_off);
		    	}
		    	
		    	return;
		    }
		});
		 
		softKeyboardDecector.setOnHiddenKeyboard(new OnHiddenKeyboardListener() {
			
		    @Override
		    public void onHiddenSoftKeyboard() {
		    	bodyLayout.setEnabled(false);
		    	
		    	if (searchTextValue.equals("")) {
		    		searchLayout.setVisibility(View.GONE);
			    	bodyButtonLayout.setVisibility(View.VISIBLE);
			    	bottomLayout.setVisibility(View.VISIBLE);
		    	}

		    	hideLayout.setVisibility(View.GONE);
		    	
		    	return;
		    }
		});
		
		fragmentReplace(isRoot);
        
        return nowView;
    }
	
	public void fragmentReplace(int reqNewFragmentIndex) {
		
		Fragment newFragment = null;
		Bundle bundle = new Bundle();
		final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
		
		switch (reqNewFragmentIndex) {
		case 1:
			categoryBt.setImageResource(R.drawable.tap_on_category);
			brandBt.setImageResource(R.drawable.tap_off_brand);
			newFragment = new ProductCategoryFm();
			break;
		case 2:
			categoryBt.setImageResource(R.drawable.tap_off_category);
			brandBt.setImageResource(R.drawable.tap_on_brand);
			newFragment = new ProductBrandFm();
			break;
		case 3:
			bundle.putString("PARAM_productTitle", searchTextValue);
			newFragment = new ProductSearchFm();
			newFragment.setArguments(bundle);
			break;
		case 4:
			bundle.putString("PARAM_brandTitle", searchTextValue);
			newFragment = new BrandSearchFm();
			newFragment.setArguments(bundle);
			break;
		}
		
	    transaction.replace(R.id.ll_fragment, newFragment);
	    transaction.commit();
    }
	
	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		switch (v.getId()) {
		case R.id.categoryBt:
			isRoot = 1;
            fragmentReplace(1);
			break;
			
		case R.id.brandBt:
			isRoot = 2;
            fragmentReplace(2);
			break;
			
		case R.id.searchProductBt:
			isRoot = 1;
			searchProductBt.setImageResource(R.drawable.search_left_on);
    		searchBrandBt.setImageResource(R.drawable.search_right_off);
			
			searchTextValue = searchText.getText().toString().trim();
			
			if (searchTextValue.equals("")) {
				Toast.makeText(getActivity(), "검색할 제품명을 입력해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			isSearch = false;
			imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
            fragmentReplace(3);
			break;
			
		case R.id.searchBrandBt:
			isRoot = 2;
			searchBrandBt.setImageResource(R.drawable.search_right_on);
    		searchProductBt.setImageResource(R.drawable.search_left_off);
			
			searchTextValue = searchText.getText().toString().trim();
			
			if (searchTextValue.equals("")) {
				Toast.makeText(getActivity(), "검색할 브랜드명을 입력해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			isSearch = false;
			imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
            fragmentReplace(4);
			break;
		}
	}

}
